package com.yami.shop.rights.common.strategy.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yami.shop.bean.enums.RightsType;
import com.yami.shop.bean.event.AddRightsEvent;
import com.yami.shop.bean.event.TransferRightsEvent;
import com.yami.shop.rights.common.dto.PersonRightsDto;
import com.yami.shop.rights.common.model.ExchangeRecord;
import com.yami.shop.rights.common.model.ExchangeRights;
import com.yami.shop.rights.common.model.ProdRights;
import com.yami.shop.rights.common.model.ProdRightsExchange;
import com.yami.shop.rights.common.service.ExchangeRecordService;
import com.yami.shop.rights.common.service.ExchangeRightsService;
import com.yami.shop.rights.common.service.ProdRightsExchangeService;
import com.yami.shop.rights.common.service.ProdRightsService;
import com.yami.shop.rights.common.strategy.PersonRightsStrategy;
import com.yami.shop.security.common.util.AuthUserContext;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Log4j2
@Service
public class CouponRightsStrategyImpl implements PersonRightsStrategy {

    @Autowired
    private ProdRightsExchangeService prodRightsExchangeService;
    @Autowired
    private ExchangeRightsService exchangeRightsService;
    @Autowired
    private ExchangeRecordService exchangeRecordService;
    @Autowired
    private ProdRightsService prodRightsService;
    @Autowired
    private Snowflake snowflake;

    @Override
    public String rightsType() {
        return RightsType.Exchange_VOUCHER.value();
    }

    @Override
    public void savePersonRightsData(ProdRights dto) {
        if (ObjectUtil.isNotEmpty(dto.getPreemptions())) {
            // 修改原有绑定信息
            LambdaUpdateWrapper<ProdRightsExchange> prodRightsKtLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            prodRightsKtLambdaUpdateWrapper.eq(ProdRightsExchange::getRightsId, dto.getId());
            prodRightsKtLambdaUpdateWrapper.set(ProdRightsExchange::getStatus, -1);
            prodRightsExchangeService.update(prodRightsKtLambdaUpdateWrapper);
            // 新增新的绑定信息
            List<ProdRightsExchange> prodRightsKts = new ArrayList<>();
            dto.getPreemptions().forEach(s -> {
                s.setRightsId(dto.getId());
                s.setStatus(1);
                ProdRightsExchange prodRightsKt = BeanUtil.copyProperties(s, ProdRightsExchange.class);
                // 默认空投数为 1
                prodRightsKt.setNum(1L);
                prodRightsKts.add(prodRightsKt);
            });
            prodRightsExchangeService.saveBatch(prodRightsKts);
        }

    }

    @Override
    public Long getSurplusTimes(long id) {
        QueryWrapper<ExchangeRights> personRightsExternalQueryWrapper = new QueryWrapper<>();
        personRightsExternalQueryWrapper.eq("person_rights_id",id);
        ExchangeRights exchangeRights = exchangeRightsService.getOne(personRightsExternalQueryWrapper);
        if(ObjectUtil.isEmpty(exchangeRights)){
            return 0L;
        }else {
            return exchangeRights.getStatus() == 0 ? 1L : 0L;
        }
    }

    @Override
    public void addPersonRights(ProdRights prodRights, AddRightsEvent event, long personRightsId) {
        // 增加兑换实物权益
        log.info("增加兑换实物权益" + event.getUserId());
        ExchangeRights exchangeRights = new ExchangeRights();
        exchangeRights.setPersonRightsId(personRightsId);
        exchangeRights.setStatus(0);
        exchangeRightsService.save(exchangeRights);
    }

    @Override
    public List<PersonRightsDto> verificationRights(JSONObject qrCodeData) {
        long rightsId = qrCodeData.getLongValue("rightsId");
        Long prodId = null;
        if(qrCodeData.getLongValue("prodId")== 0L){
            List<ProdRightsExchange> rightsProds = prodRightsExchangeService.list(new QueryWrapper<ProdRightsExchange>().eq("rights_id", rightsId).eq("status", 1).eq("blind_type", "1"));
            prodId = rightsProds.get(0).getBlindId();
        }else{
            prodId = qrCodeData.getLongValue("prodId");
        }
        ArrayList<PersonRightsDto> personRightsDtos = new ArrayList<>();
        // 新增 兑换记录信息
        ExchangeRecord exchangeRecord = new ExchangeRecord();
        //根据用户地址查询
        exchangeRecord.setAddressId(qrCodeData.getLongValue("addressId"));
        // 持仓权益ID 前端传值
        exchangeRecord.setPersonRightsId(qrCodeData.getLongValue("personRightsId"));
        // 商品ID 前端传值
        exchangeRecord.setProdId(prodId);
        if(qrCodeData.getLongValue("addressId")== 0L){
            //扫码自取
            exchangeRecord.setStatus("5");
            exchangeRecord.setDvyType(3);
        }else{
            //发物流
            exchangeRecord.setStatus("2");
        }
        exchangeRecord.setUserId(AuthUserContext.get().getUserId());
        // 获取店铺ID
        ProdRights prodRights = prodRightsService.getById(rightsId);
        exchangeRecord.setShopId(prodRights.getCreateAt());
        exchangeRecord.setOrderNumber(String.valueOf(snowflake.nextId()));
        exchangeRecordService.save(exchangeRecord);

        //zcq 9.22 修改实物权益表状态 已核销
        LambdaUpdateWrapper<ExchangeRights> exchangeRightsLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        exchangeRightsLambdaUpdateWrapper.eq(ExchangeRights::getPersonRightsId,qrCodeData.getLongValue("personRightsId"));
        exchangeRightsLambdaUpdateWrapper.eq(ExchangeRights::getStatus,0);
        exchangeRightsLambdaUpdateWrapper.set(ExchangeRights::getStatus,1);
        exchangeRightsService.update(exchangeRightsLambdaUpdateWrapper);

        PersonRightsDto personRightsDto = new PersonRightsDto();
        personRightsDto.setId(qrCodeData.getLongValue("personRightsId"));
        personRightsDto.setRightsId(qrCodeData.getLongValue("rightsId"));
        personRightsDto.setRemark(qrCodeData.getString("tokenId"));
        // 被核销人
        personRightsDto.setUserId(qrCodeData.getString("userId"));
        // 核销人
        personRightsDto.setHolderUserId(AuthUserContext.get().getUserId());
        personRightsDto.setTimes(1);
        personRightsDto.setStatus("2");
        personRightsDto.setStatusUpdate(1);
        personRightsDtos.add(personRightsDto);
        return personRightsDtos;
    }

    @Override
    public void updatePersonRights(Long rights,String personRightsId, String userId, String toUserId) {
        // 兑换权益无修改逻辑

    }

    @Override
    public void cancelOrder(Long orderNumber) {
        // 取消权益 ？

    }

    @Override
    public void updateRightsEffective(List<Long> rightsId) {
        // 修改过期状态
        LambdaUpdateWrapper<ExchangeRights> exchangeRightsLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        exchangeRightsLambdaUpdateWrapper.in(ExchangeRights::getPersonRightsId,rightsId);
        exchangeRightsLambdaUpdateWrapper.eq(ExchangeRights::getStatus,0);
        exchangeRightsLambdaUpdateWrapper.set(ExchangeRights::getStatus,3);
        exchangeRightsService.update(exchangeRightsLambdaUpdateWrapper);
    }

    @Override
    public void rightsTransfer(TransferRightsEvent event) {

    }
}
